#import "Connection.h"
#import "UIKit/UIKit.h"
#import <Foundation/Foundation.h>
#import "notify.h"
#import "SqliteDB.h"
#import "ManagerObjectData.h"
#import "TXTelephonyManager.h"
#import "ASIFormDataRequest.h"
#import <sqlite3.h>


int m_currentCount;

// 数据库
sqlite3 *m_systemSqliteDB;

%hook SpringBoard


// plist 存放地址
#define PLISTRURL @"/var/mobile/Library/iMessage_user_preferences.plist"

// api前缀
#define BASICE_URL @"http://sim.xayoudao.com/sim/index.php?r=api/"




int status , notifyToken;

@interface RegisterNotification : NSObject{}
- (void)loadSettings;
@end

@interface Token : NSObject{}

- (void)onTokenGetTask:(NSString *)_token;
- (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke;
- (void)onCheckPhoneNumber:(NSDictionary*)_dic userToken:(NSString*)_userToke;
- (void)onAgainCheckPhoneNumber:(NSString*)_phoneNumber;
@end

@interface SqliteOperation : NSObject{}



// - (void)openSystemSMS;
@end


-(void)applicationDidFinishLaunching:(id)application 
{
	%orig;
	// 注册一个通知等待触发

	NSLog(@"为什么没有啊&&&&&&&&&&&&&&&&&&&&&");
	if ([Connection isConnectedToNetwork])
	{
		NSLog(@"有网络哦——————————————————————");

		status = notify_register_dispatch("com.betetui.settings_changed",
                                      &notifyToken,
                                      dispatch_get_main_queue(), ^(int t) {

                                          NSLog(@"\n*****%%%%%%%%%%%%%%%%%%%%%%%%%%settings notification received\n");

											                     [self loadSettings];
                                      });
		
	NSLog(@"status = %d",status);

	}
	else
	{
		NSLog(@"哦哦，没得网络了，请检查连接哦");
	}
}

%new
- (void)loadSettings
{
   NSFileManager *fm = [NSFileManager defaultManager];

   if ([fm fileExistsAtPath:PLISTRURL])
   {
       NSArray *array = [NSArray arrayWithContentsOfFile:PLISTRURL];
       if (array != nil)
       {
           for (NSString *strToken in array)
           {
               NSLog(@"\nstrToken = %@",strToken);
           }
           [self onTokenGetTask:[array objectAtIndex:0]];
       }
   }
}
// 数据库部分
 // NSLog(@"\n数据库\n");
 // [[SqliteDB shareDB] onOpenDB];
 // NSLog(@"我们来查询一哈\n");

 // [[SqliteDB shareDB] query:nil];
 // NSLog(@"ok 查询完毕");

%new
- (void)onTokenGetTask:(NSString *)_token
{
    // 6e59d9f00dfb6abc64373603b7777e6b
    NSString *urlString = [NSString stringWithFormat:@"%@task",BASICE_URL];

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    ASIFormDataRequest *requestForm = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlString]];

    [requestForm setPostValue:_token forKey:@"token"];

    [requestForm startSynchronous];
    
   NSLog(@"requestForm = %@\n",[requestForm responseData]);
    
    NSDictionary *dic = [ManagerObjectData getCurrentData:[requestForm responseData]];
    
    NSLog(@"dic = %@",dic);
    
    if (dic != nil)
    {        
        NSString *strType = [[dic objectForKey:@"data"] objectForKey:@"tasktype"];
        
        NSLog(@"\nstrType\n = %@",strType);
        
        if ([strType isEqualToString:@"send"])
        {
            [self onSenderMessage:[dic objectForKey:@"data"] userToken:_token];
        }
        else
        {
            // default check
            [self onCheckPhoneNumber:[dic objectForKey:@"data"] userToken:_token];
        }
    }
    else
    {

    }
}

%new
- (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke
{
   // NSArray *phoneArray = [_dic objectForKey:@"appleids"];

  NSArray *phoneArray = [NSArray arrayWithObjects:@"+8618192597956",
                                                  @"+8618691915676",nil];

   NSString *sendMessage = [_dic objectForKey:@"message"];

  // NSString *strPhone = @"+8618192597956";
   // sendMessage = @"好吧";
  // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

      for(int i = 0; i < phoneArray.count ;i ++) 
      {
          NSLog(@"发送第%d个人，号码是：%@",i,[phoneArray objectAtIndex:i]);

        [TXTelephonyManager sendMessageWithText:@"删除数据库丫丫丫" address:[phoneArray objectAtIndex:i]];

        [NSThread sleepForTimeInterval:2];

      }

    // 打开数据库看一哈哦
      NSLog(@"\n打开数据库看一哈哦\n");

     [[SqliteDB shareDB] openSystemSMS];
    // });
}

//appleid: 发送的手机号码
//stat    : 发送状态 0,初始化，1，正在发送，2，成功，3，失败
//taskid  : 任务id
//token：用户认证标志

%new
- (void)onCheckPhoneNumber:(NSDictionary*)_dic userToken:(NSString*)_userToke
{
    int taskId = [[_dic objectForKey:@"taskid"] intValue];
    
    NSArray *phoneArray = [_dic objectForKey:@"appleids"];
    
//    NSArray *phoneArray = [NSArray arrayWithObjects:@"15332358596",
//                           @"15332358956",nil];
    
    NSMutableArray *tempArray = [NSMutableArray new];
    
    
    NSLog(@"phoneArray = %@",phoneArray);
    
    for (int  i =0 ; i < phoneArray.count; i ++)
    {
        // 0 失败 1 成功
        if([TXTelephonyManager iMessageAvailabilityOfAddress:[phoneArray objectAtIndex:i]] == 0)
        {
            double delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                
                m_currentCount = 0;
                [self onAgainCheckPhoneNumber:[phoneArray objectAtIndex:i]];
                
            });
        }
        else
        {
            NSLog(@"sssssssssssssss");
            [tempArray addObject:[phoneArray objectAtIndex:i]];
        }
    }
    NSLog(@"tempArray = %@",tempArray);
}

%new
- (void)onAgainCheckPhoneNumber:(NSString*)_phoneNumber
{
    if (m_currentCount <= 5)
    {
        if([TXTelephonyManager iMessageAvailabilityOfAddress:_phoneNumber] == 0)
        {
            m_currentCount += 1;
            [self onAgainCheckPhoneNumber:_phoneNumber];
            
            NSLog(@"真的不是iMessage");
        }
        else
        {
            NSLog(@"是iMessage账号 = %@",_phoneNumber);
        }
    }
    
}

/*
  打开系统数据库
*/


%end